package com.zj.study.utils.beancopier;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: BeanCopierTest1</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2024 版权</p>
 * <p>Company: Oceanpayment</p>
 *
 * @author Jerry Zhao
 * @version V1.0
 * @date 2024年08月05号 18点00分41秒
 */
@Slf4j
public class BeanCopierTest1<T> {

    public static void main(String[] args) {

        // 字节码拷贝
        new Thread(() -> {
            long startTime = System.currentTimeMillis();
            log.info("线程1执行开始时间:" + startTime);
            List<TestA> sourceList = new ArrayList<>();
            for (int i = 0; i < 1000000; i++) {
                TestA testA = new TestA();
                testA.setAge(i);
                sourceList.add(testA);
            }
            List<TestB> testBS = BeanCopier.copyList(sourceList, TestB.class);
            System.out.println("线程1 targetList 条数 = " + testBS.size());
            long endTime = System.currentTimeMillis();
            log.info("线程1执行结束时间:" + endTime);
            log.info("线程1执行结束执行毫秒:" + (endTime - startTime));
        }).start();

        // 反射拷贝
        new Thread(() -> {
            long startTime = System.currentTimeMillis();
            log.info("线程2执行开始时间:" + startTime);
            List<TestA> sourceList = new ArrayList<>();
            for (int i = 0; i < 1000000; i++) {
                TestA testA = new TestA();
                testA.setAge(i);
                sourceList.add(testA);
            }
            List<TestB> testBS = copyList(sourceList, TestB.class);
            System.out.println("线程2 targetList 条数 = " + testBS.size());
            long endTime = System.currentTimeMillis();
            log.info("线程2执行结束时间:" + endTime);
            log.info("线程2执行结束执行毫秒:" + (endTime - startTime));
        }).start();

    }


    public static <S, T> List<T> copyList(List<S> sourceList, Class<T> targetClass) {
        List<T> targetList = new ArrayList<>();
        try {
            for (Object source : sourceList) {
                T target= targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            }
        } catch (Exception e) {
            log.error("convert error ", e);
        }
        return targetList;
    }


}